import { App as VueApp, createApp } from 'vue';
import { createPinia } from 'pinia';
import * as QianKunHelper from 'vite-plugin-qiankun/dist/helper';
import 'element-plus/es/components/message/style/css';

import App from '@core/App.vue';
import router from './utils/router';
import { i18n } from './i18n';

let app: VueApp<Element>;

const render = (props?: QianKunHelper.QiankunProps) => {
  app = createApp(App);
  app.config.globalProperties.mainAppProps = props;
  app.use(createPinia());
  app.use(router);
  app.use(i18n);
  const container = getAppContainer(props);
  if (!container) {
    throw new Error('Can not find app container with query selector "#sub-app"');
  }
  app.mount(container);
};

const getAppContainer = (mainAppProps?: QianKunHelper.QiankunProps) => {
  if (mainAppProps?.container) {
    return mainAppProps.container.querySelector('#sub-app');
  }
  return '#sub-app';
};

QianKunHelper.renderWithQiankun({
  bootstrap() {
    // do nothing
  },
  mount(props) {
    render(props);
  },
  update() {
    // do nothing
  },
  unmount() {
    app.unmount();
  },
});

if (!QianKunHelper.qiankunWindow.__POWERED_BY_QIANKUN__) {
  render();
}
